/*
 * Copyright (c) 宜品生鲜
 */

package com.zhangfei.order.server.aop;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 打印grpc 接口出入参
 * @author ht
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class GrpcServiceLogAop {

    /**
     * //其他项目模块要使用，自己定义个pointCut 一个Before
     */
    @Pointcut("execution(public * com.zhangfei.order.server.grpc..*.*(..))")
    public void grpcService() {
        log.info("grpcService 方法调用...begin...");
    }


    /**
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("grpcService()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        String interFaceAndMethod = joinPoint.getTarget().getClass() + "/" + joinPoint.getSignature().getName();
        List<Object> list = Arrays.asList(joinPoint.getArgs());
        log.info("GrpcServiceLogAop拦截:"+interFaceAndMethod + "方法调用,参数列表:{" + list + "}");
        Object obj = joinPoint.proceed();

        try {
            //  这个暂时获取不到值，因为值在流StreamObserver
            List<Object> resultList = Arrays.asList(joinPoint.getArgs());
            Object ServerCallStreamObserverImpl = resultList.get(0);
            String str =  JSON.toJSONString(resultList);
            log.info("GrpcServiceLogAop拦截:"+"{}方法调用, 返回值:{}", interFaceAndMethod, str);
        } catch (Exception e) {
            log.error("打印参数日志异常:", e);
        }

        return obj;
    }

}
